<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { addMoreEmployees } from '@/api/employees'
// 格式化时间
import { formatExcelDate } from '@/utils/index'

export default {
  name: 'UploadExcel',
  // 导入组件名
  components: { UploadExcelComponent },
  // 父传子,接收变量名
  props: {},
  data() {
    // 这里存放数据
    return {
      tableData: [],
      tableHeader: []
    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监听器 监控 data 中的数据变化
  watch: {},
  // 方法集合
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }

      this.$message({
        message: '文件太大了',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // header 表头 result表格内容
      // console.log(results)
      // console.log(header)
      // 数据中英文转换
      const data = this.transExcel(results)
      // console.log(data)
      // 发送请求 批量添加
      this.doAdd(data)
      // 添加完成返回页面
      this.$router.back()
    },
    async doAdd(data) {
      try {
        const res = await addMoreEmployees(data)
        console.log('addMoreEmployees', res)
      } catch (err) {
        console.log('addMoreEmployees', err)
      }
    },
    // 中文转英文
    transExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // data为传入的需要转出的数据
      const keys = Object.keys(mapInfo)
      console.log(keys)
      // 对数组进行遍历
      return data.map(item => {
        const obj = {}
        keys.forEach(ele => {
          if (mapInfo[ele] === 'timeOfEntry' || mapInfo[ele] === 'correctionTime') {
            obj[mapInfo[ele]] = formatExcelDate(item[ele])
          } else {
            obj[mapInfo[ele]] = item[ele]
          }
        })
        return obj
      })
    }

  }
}
</script>

<style scoped>
</style>
